package com.nnxy.controller;

import com.nnxy.pojo.Result;
import com.nnxy.pojo.User;
import com.nnxy.service.UserService;
import com.nnxy.utils.JwtUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;


@RestController
public class CommonController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null ||
                user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
            return new Result(0, "用户名或密码不能为空", null);
        }

        user = userService.findUser(user);
        if (user == null) {
            return new Result(0, "登录失败", null);
        }

        String jwt = JwtUtils.generateToken(user);
        user.setToken(jwt);
        user.setPassword("");
        return new Result(1, "success", user);
    }

    /**
     * 处理文件上传请求， 将前端传递过来的文件存储到D:\imgs目录下
     * @param file
     * @return
     * MultipartFile file 接收文件上传对象，注意file是前端的上传文件请求数据的名字
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        //1.获取原始文件名
        String originalFilename = file.getOriginalFilename(); //2.jpg
        //获取文件扩展名
        String extFileName = originalFilename.substring(originalFilename.lastIndexOf("."));//.jpg

        //2.生成新的唯一文件名(xxxx.jpg) = uuid + 文件扩展名
        //UUID，通用唯一码，可以生成36位唯一值，里面包含4个“-”，一般推荐去掉，就剩下32位字符
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + extFileName;//xxxxxxxxxxxxxxxxxxxxxxxxxxxx.jpg

        try {
            //3.存储到D:\imgs目录下, 注意File导入包位java.io.File
            file.transferTo(new File("D:\\images",newFileName));

            //4.封装Result返回数据
            //前端需要时一个访问资源完整url = "/api/download?fileName=xxxxxx.jpg"
            String url = "/api/download?fileName="+newFileName;
            return new Result(1,"文件上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(0,"文件上传失败:"+e.getMessage(),null);
        }
    }

    /**
     * 处理图片下载请求
     * @param response
     * @param fileName
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response,String fileName) throws Exception {
        //1.获取磁盘对应文件输入流: 本质读取磁盘上这个图片文件
        InputStream input = new FileInputStream("D:\\images\\" + fileName);

        //2.将输入流数据给到浏览器输出流程， response.getOutputStream() 浏览器输出流程
        IOUtils.copy(input,response.getOutputStream());//浏览器就可以展现这个图片文件了
    }
}